package com.techq.weibo;


import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.techq.weibo.meta.User;
import com.techq.weibo.robot.CrawlRobot;
import com.techq.weibo.robot.imp.SinaWeiboCrawler;
import com.techq.weibo.share.exception.ShareException;
 
public class Login {
 
	private final static HttpClient client = new DefaultHttpClient();
 
	
	/**
	 * 抓取网页
	 * 
	 * @param url
	 * @throws IOException
	 */
	static String get(String url) throws IOException {
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		
		printCookies();  
        
		System.out.println(response.getStatusLine());
		HttpEntity entity = response.getEntity();
 
		String result = dump(entity);
		get.abort();
 
		return result;
	}

	private static void printCookies() throws IOException {
		FileWriter fw = new FileWriter("C:/cookie.txt");   
        List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();    
        if (cookies.isEmpty()) {    
            System.out.println("None");    
        } else {    
            for (int i = 0; i < cookies.size(); i++) {  
                System.out.println("- " + cookies.get(i).toString());  
                fw.write(cookies.get(i).toString()+"\r\n");   
            }    
        }  
        fw.close();
	}
 


	private static void redirect(HttpResponse response) throws IOException {
		// 新浪微博登录没有301，302之类的跳转；而是返回200，然后用javascript实现的跳转
		// int statusCode = response.getStatusLine().getStatusCode();
		// if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
		// || (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
		// || (statusCode == HttpStatus.SC_SEE_OTHER)
		// || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		// // 此处重定向处理 此处还未验证
		// String newUri = response.getLastHeader("Location").getValue();
		// get(newUri);
		// }
 
		// Get hold of the response entity
		HttpEntity entity = response.getEntity();
		// 取出跳转的url
		// location.replace("http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&ticket=ST-MTkxODMxOTI0Nw==-1309224549-xd-263902F174B27BAB9699691BA866EFF2&retcode=0");
		String location = getRedirectLocation(dump(entity));
		get(location);
	}

	private static HttpPost initParams(String user, String pwd)
			throws UnsupportedEncodingException {
		HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);  
		
		HttpPost post = new HttpPost(
				"http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.14)");
		//		 http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.14)
		post.setHeader("Host", "login.sina.com.cn");
		post.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0");
		post.setHeader("Referer", "http://weibo.com/");
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
		// 登录表单的信息
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("entry", "miniblog"));
		qparams.add(new BasicNameValuePair("gateway", "1"));
		qparams.add(new BasicNameValuePair("from", ""));
		qparams.add(new BasicNameValuePair("savestate", "0"));
		qparams.add(new BasicNameValuePair("useticket", "1"));
		qparams.add(new BasicNameValuePair("ssosimplelogin", "1"));
		qparams.add(new BasicNameValuePair("service", "miniblog"));
		// servertime=1309164392
		// nonce=PJZCHM
		// qparams.add(new BasicNameValuePair("pwencode", "wsse"));
		qparams.add(new BasicNameValuePair("encoding", "utf-8"));
		qparams.add(new BasicNameValuePair(
				"url",
				"http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));
		qparams.add(new BasicNameValuePair("returntype", "META"));
 
		qparams.add(new BasicNameValuePair("username", user));
		qparams.add(new BasicNameValuePair("password", pwd));
 
		UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, "UTF-8");
		post.setEntity(params);
		return post;
	}
 
	private static String getRedirectLocation(String content) {
		String regex = "location\\.replace\\(\"(.*?)\"\\)";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(content);
 
		String location = null;
		if (matcher.find()) {
			location = matcher.group(1);
		}
 
		return location;
	}
 
	/**
	 * 打印页面
	 * 
	 * @param entity
	 * @throws IOException
	 */
	private static String dump(HttpEntity entity) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				entity.getContent(), "utf8"));
		
		StringBuilder sb = new StringBuilder(50000);
		String line;
		while((line = br.readLine()) != null) {
			sb.append(line + "\n\t");
		}
		//System.out.println(sb.toString());
		return sb.toString();
		//while((line = br.readLine()) != 
	}
 
	
	/**
	 * 执行登录过程
	 * 
	 * @param user
	 * @param pwd
	 * @param debug
	 * @throws IOException
	 */
	static void login(String user, String pwd) throws IOException {
		HttpPost post = initParams(user, pwd);
		HttpResponse response = client.execute(post);
		post.abort();
		System.out.println("redirect");
		redirect(response);
	}
	
	
	public static void main(String[] args) throws IOException {
//		System.out.println("login");
//		login("luanlexi@163.com", "chen1234");
//		String result = get("http://weibo.com/");
//		System.out.println(result);
		CrawlRobot robot = new SinaWeiboCrawler();
		try {
			robot.auth("http://weibo.com/", new User("luanlexi@163.com", "chen1234"));
			StringBuilder result = robot.get("http://weibo.com/");
			System.out.println(result.toString());
		} catch (ShareException e) {
			// TODO Auto-generated catch block
			e.printStackTrace(System.out);
		}
	}
}